package com.wee.aircoach_user;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wee.entity.Play_list;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Solomon on 2015/11/26.
 */
public class VideoViewActivity extends Activity {

    private final String TAG = "main";

    // private EditText et_path;

    private ImageButton btn_play, btn_next, btn_last, btn_stop, btn_again;

    private VideoView vv_video;

    private boolean isPlaying;
    List<Integer> list=new ArrayList();
    // 每个的循环次数
    int count = 0;
    // list集合第几个
    int i = 0;
    int h = 2;

    private ArrayList<Play_list> mDatas = new ArrayList<Play_list>();

    // 计时
    private int recLen = 0;
    private TextView timer_text, jump;
    private LinearLayout jishi;
    private LinearLayout linear;
    private RelativeLayout video;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Activity标题不显示
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 设置全屏显示
        setContentView(R.layout.activity_videoview);
        linear = (LinearLayout) findViewById(R.id.linear);
        jishi = (LinearLayout) findViewById(R.id.jishi);
        video = (RelativeLayout) findViewById(R.id.video);
        timer_text = (TextView) findViewById(R.id.timer);

        jump = (TextView) findViewById(R.id.jump);

        vv_video = (VideoView) findViewById(R.id.vv_videoview);

        btn_play = (ImageButton) findViewById(R.id.btn_play);

        btn_next = (ImageButton) findViewById(R.id.btn_next);

        btn_last = (ImageButton) findViewById(R.id.btn_last);

        btn_stop = (ImageButton) findViewById(R.id.btn_stop);

        btn_again = (ImageButton) findViewById(R.id.btn_again);

        btn_play.setOnClickListener(click);

        btn_next.setOnClickListener(click);

        btn_last.setOnClickListener(click);

        btn_stop.setOnClickListener(click);

        btn_again.setOnClickListener(click);

        video.setOnClickListener(click);

        jump.setOnClickListener(click);

        init();

    }

    // 强制横屏
    @Override
    protected void onResume() {
        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }

    @SuppressWarnings("unchecked")
    private void init() {
        ImageView imageView = (ImageView)findViewById(R.id.bg_rest);
        ImageLoader.getInstance().displayImage("drawable://" + R.drawable.rest_play, imageView);
        Intent intent = getIntent();
        mDatas = (ArrayList<Play_list>) intent.getSerializableExtra("kangning");

    }

    // rest 休息时间

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) { // handle message
            switch (msg.what) {
                case 1:
                    recLen--;
                    timer_text.setText("" + recLen);

                    if (recLen > 0) {
                        Message message = handler.obtainMessage(1);
                        handler.sendMessageDelayed(message, 1000); // send message
                    } else {
                        // timer_text.setVisibility(View.GONE);
                        jishi.setVisibility(View.GONE);
                        next();
                    }
                    break;
                case 0:
                    jishi.setVisibility(View.GONE);
                    recLen = 0;
                    break;

            }

            super.handleMessage(msg);
        }
    };

    private View.OnClickListener click = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                /** 开始 */
                case R.id.btn_play:
                    play(0);
                    btn_play.setVisibility(View.GONE);
                    btn_again.setVisibility(View.VISIBLE);
                    linear.setVisibility(View.GONE);
                    break;
                /** 下一个 */
                case R.id.btn_next:

                    next1();
                    linear.setVisibility(View.GONE);
                    break;
                /** 上一个 */
                case R.id.btn_last:

                    last();
                    linear.setVisibility(View.GONE);
                    break;
                /** 停止 */
                case R.id.btn_stop:
                    showUpdateDialog();
                    break;

                /** 继续播放 */
                case R.id.btn_again:

                    vv_video.start();
                    linear.setVisibility(View.GONE);
                    break;
                /** 全屏点击暂停 */

                case R.id.video:

                    vv_video.pause();
                    linear.setVisibility(View.VISIBLE);
                    break;

                case R.id.jump:
                    handler.sendEmptyMessage(0);

                    break;

                default:

                    break;

            }

        }

    };

    private void showUpdateDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle("训练尚未结束，你确定结束今天的训练吗？");
        builder.setCancelable(false);
        builder.setPositiveButton("再练一会", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                vv_video.start();
                linear.setVisibility(View.GONE);
            }
        });
        builder.setNegativeButton("结束训练", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
           finish();
            }
        });
//
        builder.create().show();
    }


    protected void play(int msec) {
        try{
            if(mDatas.get(i).getType().equals("video")){
                vv_video.setVideoPath("/storage/emulated/0/VideoAirCache/"
                        + mDatas.get(i).getId() + ".mp4");
            }else{
                next();
            }

        }catch (Exception r){
        }

        Log.i(TAG, "开始播放");

        vv_video.start();

        // 按照初始位置播放

        // 播放之后设置播放按钮不可用
        btn_play.setEnabled(false);

        vv_video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {

                cycle();

            }

        });

        vv_video.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {

                // 发生错误重新播放

                play(0);

                isPlaying = false;

                return false;

            }

        });

    }

    /**
     *
     * 循环播放
     * */
    protected void cycle() {
        // TODO Auto-generated method stub
        if (count < mDatas.get(i).getCount() - 1) {
            vv_video.start();
            count++;
        } else {
            next();
            stop();
        }
    }

    /**
     *
     * 循环中的下一个
     * */
    protected void next() {
        try {
            if (i < mDatas.size()) {
                i++;
                if (mDatas.get(i).getType().equals("video")) {
                    replayer();
                } else if (mDatas.get(i).getType().equals("rest")) {
                    rest();
                } else {
                    next();
                }

            } else {
                /*Toast.makeText(VideoViewActivity.this, "当前是最后一个视频",
                        Toast.LENGTH_LONG).show();*/
                startActivity(new Intent(VideoViewActivity.this, PlayendActivity.class));
                finish();
            }
        } catch (Exception e) {
           /* Toast.makeText(VideoViewActivity.this, "当前是最后一个视频",
                    Toast.LENGTH_LONG).show();*/
            startActivity(new Intent(VideoViewActivity.this, PlayendActivity.class));
            finish();


        }
        // TODO Auto-generated method stub
    }

    /** 播放指定的视频 */
    private void replayer() {
        vv_video.setVideoURI(Uri.parse("/storage/emulated/0/VideoAirCache/"
                + mDatas.get(i).getId() + ".mp4"));
        vv_video.start();
        count = 0;
    }

    /** 休息控制 */
    private void rest() {
        vv_video.pause();
        recLen = mDatas.get(i).getCount();
        timer_text.setText("" + recLen);
        jishi.setVisibility(View.VISIBLE);
        // handler.postDelayed(runnable, 1000);
        Message message = handler.obtainMessage(1); // Message
        handler.sendMessageDelayed(message, 1000);

    }

    /** 上一个 */
    protected void last() {
        try {
            if (i < mDatas.size() || i >0) {
                i--;
                if (mDatas.get(i).getType().equals("pos_start")) {
                    h--;
                    if(h>0){
                        last();
                    }else{
                        i++;
                        replayer();
                        h=2;
                    }
                } else if (!mDatas.get(i).getType().equals("pos_start")) {
                    last();
                }
            } else {
                Toast.makeText(VideoViewActivity.this, "当前是第一个动作",
                        Toast.LENGTH_LONG).show();
            }

        } catch (Exception e) {
            Toast.makeText(VideoViewActivity.this, "当前是第一个动作 ",
                    Toast.LENGTH_LONG).show();
            vv_video.setVideoURI(Uri.parse("/storage/emulated/0/VideoAirCache/"
                    + mDatas.get(1).getId() + ".mp4"));
            vv_video.start();
            count = 0;
            next();

        }

    }
/**多个小视频 组成阶段视频
 * pos_start 等作为标识 标记下一个视频为
 * 阶段视频开头  所以 检测这个标识
 *  然后下个就是 正式小段视频 进行播放
 * 循环进行检测  last()方法同理  **/
    /** 下一个 */
    protected void next1() {
        try {
            if (i < mDatas.size()) {
                i++;
                if (mDatas.get(i).getType().equals("pos_start")) {
                    i++;
                    if(mDatas.get(i).getType().equals("video")){
                        replayer();
                    }else{
                        next1();
                    }
                } else if (!mDatas.get(i).getType().equals("pos_start")) {
                    next1();
                } else {
                }
            } else {
                try{   next();}catch (Exception e){
                    Toast.makeText(VideoViewActivity.this,"有问题Video",Toast.LENGTH_SHORT).show();
                }
             /*   Toast.makeText(VideoViewActivity.this, "当前最后第一个00",
                        Toast.LENGTH_LONG).show();*/
            }

        } catch (Exception e) {
            next();
            try{   next();}catch (Exception r){
                Toast.makeText(VideoViewActivity.this,"有问题Video",Toast.LENGTH_SHORT).show();
            }
          /*  Toast.makeText(VideoViewActivity.this, "当前是最后一个00",
                    Toast.LENGTH_LONG).show();*/
        }

    }

    /**
     *
     * 停止播放
     */
    protected void stop() {

        if (vv_video != null && vv_video.isPlaying()) {

            vv_video.stopPlayback();

            btn_play.setEnabled(true);

            isPlaying = false;

        }

    }

    /**
     *
     * 全屏播放
     */


}

